package com.zf.rpc.transport.socket.server;

import com.zf.rpc.entity.RpcRequest;
import com.zf.rpc.entity.RpcResponse;
import com.zf.rpc.handler.RequestHandler;
import com.zf.rpc.provider.ServiceProvider;
import com.zf.rpc.registry.ServiceRegistry;
import com.zf.rpc.serializer.CommonSerializer;
import com.zf.rpc.transport.socket.util.ObjectReader;
import com.zf.rpc.transport.socket.util.ObjectWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;

/**
 * @ProjectName: RPC-zhaofeng
 * @Package: com.zf.rpc.transport
 * @ClassName: RequestHanderThread
 * @Author: zf
 * @Description:
 * @Date: 2021/5/7 15:01
 * @Version: 1.0
 */
public class RequestHandlerThread implements Runnable{
    private static final Logger logger = LoggerFactory.getLogger(RequestHandlerThread.class);

    private Socket socket;
    private RequestHandler requestHandler;

    private CommonSerializer serializer;


    public RequestHandlerThread(Socket socket, RequestHandler requestHandler, ServiceRegistry serviceRegistry, CommonSerializer serializer) {
        this.socket = socket;
        this.requestHandler = requestHandler;

        this.serializer = serializer;
    }

    @Override
    public void run() {
        try (InputStream inputStream= socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {
            RpcRequest rpcRequest = (RpcRequest) ObjectReader.readObject(inputStream);

            Object result = requestHandler.handle(rpcRequest);
            RpcResponse<Object> response = RpcResponse.success(result,rpcRequest.getRequestId());
            ObjectWriter.writeObject(outputStream, response, serializer);

        } catch (IOException e) {
            logger.error("调用或发送时有错误发生：", e);
        }

    }
}
